/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ez2find.manager;

import com.ez2find.model.Area;
import com.ez2find.model.Event;
import com.ez2find.model.CategoriaEvento;
import com.ez2find.model.RegisterUser;
import com.ez2find.model.Site;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Owner
 */
@Stateless
public class EventManagerBean implements EventManagerLocal {
    
    @PersistenceContext
    private EntityManager em;
    
    public void create(Event event)throws Exception {
        em.persist(event);
    }
 
    public void update(Event event)throws Exception {
        em.merge(event);
    }

    public Event merge(Event event)throws Exception {
        return em.merge(event);
    }
    
    public void delete(Event event)throws Exception {
        event=em.merge(event);
        em.remove(event);
    }
    
    public Event find(long id){
        return em.find(Event.class,id);
    }

    public List<Event> listAll(){
        Query query=em.createNamedQuery("listAllEvents");
        List<Event> result=query.getResultList();
        return result;
    }
    
    public long lastCode(){
        try{
            Query query=em.createNamedQuery("lastEventCode");
            return (Long) query.getSingleResult();
        }catch(Exception ex){
            return 0;
        }
    }
    
    public List<Event> listEventsSite(Site site, boolean eventC, CategoriaEvento eventCategorie, boolean forD, Date date, String consult){
        Query query=em.createQuery("SELECT e FROM Event e WHERE e.site=:site AND e.status='active'"+consult+" ORDER BY e.publishDate DESC, e.code DESC");
        query.setParameter("site", site);
        if(eventC)
            query.setParameter("eventCategorie", eventCategorie);
        if(forD){
            query.setParameter("startDate", date);
            query.setParameter("endDate", date);
        }
        List<Event> result=query.getResultList();
        return result;
    }
    
    public List<Event> listEventsArea(Area area, boolean eventC, CategoriaEvento eventCategorie, boolean forD, Date date, String consult){
        Query query=em.createQuery("SELECT e FROM Event e WHERE e.area=:area AND e.status='active'"+consult+" ORDER BY e.publishDate DESC, e.code DESC");
        query.setParameter("area", area);
        if(eventC)
            query.setParameter("eventCategorie", eventCategorie);
        if(forD){
            query.setParameter("startDate", date);
            query.setParameter("endDate", date);
        }
        List<Event> result=query.getResultList();
        return result;
    }
    
}
